
import { ref, onMounted, onBeforeUnmount } from 'vue';

export default function scanner(callback, timeout = 100) {
    const code = ref('');
    const lastTime = ref(Date.now());

    const handleKeydown = (e) => {
        console.log(e.keyCode);
        if (Date.now() - lastTime.value > timeout) code.value = '';
        if (e.keyCode >= 32 && e.keyCode <= 126) code.value += e.key;
        if (e.keyCode === 13 && code.value) {
            callback(code.value);
            code.value = '';
        }
        lastTime.value = Date.now();
    };
    const close = () => {

        document.removeEventListener('keydown', handleKeydown)
    }
    const open = () => {
        document.addEventListener('keydown', handleKeydown)
    }
    onMounted(() => close);
    onBeforeUnmount(() => open);

    return { code, close, open }; // 可选暴露数据
}
